(function($) {
    $.fn.jslide = function(options) {
        var defaults = {
            renderTo: $(document.body),
            enable: true,
            initPosition: 'max',
            size: {barWidth: 200, sliderWidth: 5},
            barCssName: 'defaultbar',
            completedCssName: 'jquery-completed',
            sliderCssName: 'jquery-jslider',
            sliderHover: 'jquery-jslide-hover',
            onChanging: function(left, e) {
//        console.log(left);
//        completedbar.css('width',left);
//                alert("onchanging");
            },
            onChanged: function(left, e) {
//                alert("onchanged");
            }
        };
        var opts = $.extend({}, defaults, options);
        opts.renderTo = typeof opts.renderTo == "string" ? $(opts.renderTo) : opts.renderTo;

        var sliderbar = $("<div><div></div><div></div></div>").attr('class', opts.barCssName).css('width', opts.size.barWidth).appendTo(opts.renderTo);
        var completedbar = sliderbar.find('div:eq(0)').attr('class', opts.completedCssName);
        var slider = sliderbar.find('div:eq(1)').attr('class', opts.sliderCssName).css('width', opts.size.sliderWidth);

        var bw = sliderbar.width();
        var sw = slider.width();

        opts.limited = {min: 0, max: bw - sw};


        if (typeof window.$sliderProcess == "undefined") {
//            window.$sliderProcess = new Function('obj1', 'obj2', 'left', 'obj1.css(\'left\',left);obj2.css(\'width\',left);');
            window.$sliderProcess = function(obj1, obj2, left) {
                obj1.css('left', left);
                obj2.css('width', left);
            };
        }

        $sliderProcess(slider, completedbar, eval('opts.limited.' + opts.initPosition));

        var slide = {
            drag: function(e) {
                var d = e.data;
                var l = Math.min(Math.max(e.pageX - d.pageX + d.left, opts.limited.min), opts.limited.max);
                $sliderProcess(slider, completedbar, l);
                opts.onChanging(l / opts.limited.max, e);
            },
            drop: function(e) {
                slider.removeClass(opts.sliderHover);
                opts.onChanged(parseInt(slider.css('left')) / opts.limited.max, e);
                $(document).unbind('mousemove', slide.drag).unbind('mouseup', slide.drop);
            }
        };

        if (opts.enable) {
            slider.bind('mousedown', function(e) {
//                console.log(slider);
//console.log(slider.css('left'));
                var d = {
                    left: parseInt(slider.css('left')),
                    pageX: e.pageX
                };
                $(this).addClass(opts.sliderHover);
                $(document).bind('mousemove', d, slide.drag).bind('mouseup', d, slide.drop);
            });
        }

    };    
})(jQuery);